package com.server.core.util;

import com.server.core.anno.Controller;
import com.server.core.config.BasicConfig;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class PackageScanUtil {

    public static String path = BasicConfig.path;
    public static String packagePath = BasicConfig.packagePath;
    public static List<String> classeFilePath = new ArrayList<>();
    private List<Class> classes = null;
    private static PackageScanUtil packageScanUtil = new PackageScanUtil();

    public static PackageScanUtil getInstance() {
        return packageScanUtil;
    }

    /**
     * @desc 搜索到所有的有@Controller的注解
     *
     * @param dir
     * @param cs
     * @return
     */
    public synchronized List<Class> packageScan(String dir, Class cs) {
        if (classes != null) {
            return classes;
        }
        classes = new ArrayList<>();
        URL location = BasicConfig.class.getProtectionDomain().getCodeSource().getLocation();
        String classPath = BasicConfig.class.getResource("/").getPath();
//        String classPath = location.getPath();
//        System.out.println("classPath:  " + classPath);
        findClass(classPath + path);

        //解析classFilePath中的class
        try {
            for (String s : classeFilePath) {
                Class clazz = Class.forName(packagePath + "." + s);

                if (clazz.getClass().isInstance(cs)) {
                    if (clazz.getAnnotation(Controller.class) != null) {
                        classes.add(clazz);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return classes;
    }

    /**
     * @desc 递归的搜索到所有的class
     *
     * @param dir
     */
    public static void findClass(String dir) {
        File file = new File(dir);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                findClass(f.getAbsolutePath());
            }
        } else if (file.getName().endsWith(".class")) {
            classeFilePath.add(file.getName().substring(0, file.getName().indexOf(".")));
        }
    }
}
